package com.springboot.demo.config;

import com.springboot.demo.shiro.ShiroRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author peter
 * @title: ShiroConfig
 * @projectName springAll-peter
 * @description: Shiro 配置类
 * @date 19-9-19上午10:24
 */
@Configuration
public class ShiroConfig {
    /**
     * 需要注意的是filterChain基于短路机制，即最先匹配原则，如：
     * <p>
     * /user/**=anon
     * /user/aa=authc 永远不会执行
     *
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //登录的URL
        shiroFilterFactoryBean.setLoginUrl("/login");
        //登录成功后跳转的URL
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //未授权URL
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        //定义filterChain,静态资源不拦截
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/img/**,", "anon");

        //druid数据源监控页面不拦截
        filterChainDefinitionMap.put("/druid/**", "anon");

        //配置退出过滤器，其中具体的退出代码shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/", "anon");
        //除上意外所有URL都必须认证通过才可以访问，未通过认证自动访问LoginURL
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager() {
        // 配置SecurityManager，并注入shiroRealm
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealm());
        return securityManager;
    }


    @Bean
    public ShiroRealm shiroRealm() {
        // 配置Realm，需自己实现
        return new ShiroRealm();
    }


}
